package com.example.myapplication.ui.home;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.example.myapplication.R;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment {
    private static final String TAG = "HomeFragment";
    private ViewPager viewPager;
    private LinearLayout dotsLayout;
    private GridView courseGrid;
    private GridLayout categoryLayout;

    private List<Banner> banners = new ArrayList<>();
    private List<Category> categories = new ArrayList<>();
    private List<Course> courses = new ArrayList<>();

    private Handler handler = new Handler();
    private Runnable runnable;
    private int currentPage = 0;
    private static final long DELAY_MS = 3000;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_home, container, false);
        initViews(root);
        loadMockData();
        return root;
    }

    private void initViews(View view) {
        viewPager = view.findViewById(R.id.viewPager);
        dotsLayout = view.findViewById(R.id.dotsLayout);
        categoryLayout = view.findViewById(R.id.categoryLayout);
        courseGrid = view.findViewById(R.id.courseGrid);
    }

    private void loadMockData() {
        Log.d(TAG, "开始加载模拟数据");

        // 1. 轮播图数据
        banners.clear();
        banners.add(new Banner("1",
                "https://img95.699pic.com/xsj/10/1v/5k.jpg", // Android课程图片
                "Android开发入门",
                "1")); // 对应课程ID
        banners.add(new Banner("2",
                "https://img95.699pic.com/xsj/07/2c/8i.jpg", // Java课程图片
                "Java基础实战",
                "2")); // 对应课程ID
        banners.add(new Banner("3",
                "https://img95.699pic.com/xsj/0s/6b/2b.jpg", // UI设计课程图片
                "UI设计原理",
                "3")); // 对应课程ID
        banners.add(new Banner("4",
                "https://img95.699pic.com/xsj/01/9s/3b.jpg", // Python课程图片
                "Python入门到精通",
                "4")); // 对应课程ID
        setupViewPager();

        // 2. 分类数据
        categories.clear();
        categories.add(new Category("1", "编程",
                "https://img95.699pic.com/xsj/0m/5b/2g.jpg",
                ""));
        categories.add(new Category("2", "设计",
                "https://img95.699pic.com/xsj/0r/3p/8n.jpg",
                ""));
        categories.add(new Category("3", "英语",
                "https://img95.699pic.com/xsj/0k/47/7i.jpg",
                ""));
        categories.add(new Category("4", "职场",
                "https://img95.699pic.com/xsj/06/1c/1e.jpg",
                ""));
        setupCategories();

        // 3. 推荐课程数据
        courses.clear();
        courses.add(new Course("1",
                "https://img95.699pic.com/xsj/10/1v/5k.jpg",
                "Android开发入门",
                "张老师", "初级", 4.8f,
                ""));
        courses.add(new Course("2",
                "https://img95.699pic.com/xsj/07/2c/8i.jpg",
                "Java基础实战",
                "李老师", "入门", 4.6f,
                ""));
        courses.add(new Course("3",
                "https://img95.699pic.com/xsj/0s/6b/2b.jpg",
                "UI设计原理",
                "王老师", "中级", 4.9f,
                ""));
        courses.add(new Course("4",
                "https://img95.699pic.com/xsj/01/9s/3b.jpg",
                "Python入门到精通",
                "赵老师", "初级", 4.7f,
                ""));
        setupCourses();
    }

    private void setupViewPager() {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getContext(), banners);
        viewPager.setAdapter(adapter);
        addDotsIndicator(0);

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                addDotsIndicator(position);
                currentPage = position;
            }
            @Override public void onPageScrolled(int position, float offset, int pixels) {}
            @Override public void onPageScrollStateChanged(int state) {}
        });
        startAutoScroll();
    }

    private void addDotsIndicator(int position) {
        dotsLayout.removeAllViews();
        for (int i = 0; i < banners.size(); i++) {
            ImageView dot = new ImageView(getContext());
            dot.setImageResource(i == position ?
                    R.drawable.ic_dashboard_black_24dp : R.drawable.ic_home_black_24dp);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(20, 20);
            params.setMargins(4, 0, 4, 0);
            dot.setLayoutParams(params);
            dotsLayout.addView(dot);
        }
    }

    private void startAutoScroll() {
        if (banners.isEmpty()) return;
        runnable = new Runnable() {
            @Override
            public void run() {
                currentPage = (currentPage + 1) % banners.size();
                viewPager.setCurrentItem(currentPage, true);
                handler.postDelayed(this, DELAY_MS);
            }
        };
        handler.postDelayed(runnable, DELAY_MS);
    }

    private void setupCategories() {
        categoryLayout.removeAllViews();
        for (int i = 0; i < categories.size(); i++) {
            View item = LayoutInflater.from(getContext()).inflate(R.layout.item_category, null);
            ImageView icon = item.findViewById(R.id.categoryIcon);
            TextView name = item.findViewById(R.id.categoryName);
            final Category category = categories.get(i);

            Glide.with(this)
                    .load(category.getIconUrl())
                    .placeholder(R.drawable.placeholder_image)
                    .error(R.drawable.error_image)
                    .into(icon);
            name.setText(category.getName());

            GridLayout.LayoutParams params = new GridLayout.LayoutParams();
            params.width = 0;
            params.height = GridLayout.LayoutParams.WRAP_CONTENT;
            params.columnSpec = GridLayout.spec(i % 4, 1f);
            params.setMargins(8, 8, 8, 8);
            item.setLayoutParams(params);

            // 添加分类点击跳转
            item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 跳转到分类列表页面
                    Intent intent = new Intent(getActivity(), CategoryListActivity.class);
                    intent.putExtra("categoryId", category.getId());
                    intent.putExtra("categoryName", category.getName());
                    startActivity(intent);
                }
            });

            categoryLayout.addView(item);
        }
    }

    private void setupCourses() {
        Log.d(TAG, "设置课程列表，课程数量: " + courses.size());

        CourseAdapter adapter = new CourseAdapter(getContext(), courses);
        courseGrid.setAdapter(adapter);

        // 课程点击事件 - 跳转到详情页
        courseGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Course course = courses.get(position);
                Log.d(TAG, "点击课程: " + course.getTitle() + "，ID: " + course.getId());

                // 先显示Toast确认点击有效
                Toast.makeText(getContext(), "正在打开: " + course.getTitle(), Toast.LENGTH_SHORT).show();

                // 跳转到详情页
                Intent intent = new Intent(getContext(), CourseDetailActivity.class);
                intent.putExtra("courseId", course.getId());
                startActivity(intent);
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (handler != null && runnable != null) {
            handler.removeCallbacks(runnable);
        }
    }
}